/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include "se_defines.h"

SE_GLOBALS()

struct Data {
  uint64_t f1;
  uint64_t f2;
  uint64_t f3;
};

struct Input {
  char buf[0x10];
  Data* data;
};

Data* data;

void test_case(std::string content) {
  int res =
      posix_memalign(reinterpret_cast<void**>(&data), 0x10000, sizeof(Data));
  if (res != 0) {
    fprintf(stderr, "posix_memalign failed: %d\n", res);
    return;
  }
  memset(data, 0x0, sizeof(Data));

  Input input = {};
  input.data = data;

  strcpy(input.buf, content.data());
  input.data->f1 = 0xdeadbeef;

  if (data->f1 == 0x0) {
    SE_STEP(true);
  }
  if (data->f3 == 0xdeadbeef) {
    SE_TARGET_STATE(true);
  }

  free(data);
}

int main(int argc, char* argv[]) {
  std::istream* input;
  std::ifstream file;
  if (argc < 2) {
    input = &std::cin; // No file name provided, read from stdin
  } else {
    file.open(argv[1]);
    if (!file) {
      std::cerr << "Could not open the file.\n";
      return 1;
    }
    input = &file; // File opened successfully, read from file
  }
  std::string content(
      (std::istreambuf_iterator<char>(*input)),
      std::istreambuf_iterator<char>());
  test_case(content);
  return 0;
}
